package db.seed;

import com.mai4j.maiadmin.setup.Helper;
import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;

import java.time.LocalDateTime;

import static com.mai4j.maiadmin.generated.Tables.USER;
import static com.mai4j.maiadmin.generated.Tables.USER_PASSWORD_AUTH;
import static db.seed.V20230404162223__Insert_UserGroup.ADMIN_GROUP_ID;
import static org.jooq.impl.DSL.using;


/**
 * 初始化的超级用户
 */
@Slf4j
public class V20230404162339__Insert_Superuser extends BaseJavaMigration {

    @Override
    public void migrate(Context context) {
        long userId = Helper.next();
        using(context.getConnection())
                .insertInto(USER)
                .columns(
                        USER.USER_ID,
                        USER.USER_GROUP_ID,
                        USER.ACCOUNT,
                        USER.NAME,
                        USER.EMAIL,
                        USER.TELEPHONE,
                        USER.GENDER,
                        USER.IP,
                        USER.USER_AGENT,
                        USER.STATUS,
                        USER.DATE_LAST,
                        USER.DATE_ADDED
                )
                .values(userId,
                        ADMIN_GROUP_ID,
                        "admin",
                        "admin",
                        "admin@example.com",
                        "+8600000000000",
                        "male",
                        "0.0.0.0",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36",
                        (byte) 1, LocalDateTime.now(), LocalDateTime.now()).execute();
        String salt = Helper.rand(8);
        String password = "00000000";
        using(context.getConnection()).insertInto(USER_PASSWORD_AUTH).columns(
                USER_PASSWORD_AUTH.USER_ID,
                USER_PASSWORD_AUTH.PASSWORD,
                USER_PASSWORD_AUTH.SALT,
                USER_PASSWORD_AUTH.ENABLE,
                USER_PASSWORD_AUTH.DATE_ADDED
        ).values(userId, Helper.password(password, salt), salt, (byte) 1, LocalDateTime.now()).execute();
        log.info("The superuser password: {}", password);
    }
}
